package Set_and_Dict;

/*
四数之和
给你一个由 n 个整数组成的数组nums ，和一个目标值 target 。
请你找出并返回满足下述全部条件且不重复的四元组[nums[a], nums[b], nums[c], nums[d]]（若两个四元组元素一一对应，则认为两个四元组重复）：
0 <= a, b, c, d< n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。

示例 1：
输入：nums = [1,0,-1,0,-2,2], target = 0
输出：[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2：
输入：nums = [2,2,2,2,2], target = 8
输出：[[2,2,2,2]]

作者：LeetCode
链接：https://leetcode.cn/leetbook/read/all-about-lockup-table/xh5n2t/
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _33四数之和 {
    public static void main(String[] args) {
        int[] arr = {1000000000,1000000000,1000000000,1000000000};
        fourSum(arr,-294967296);
//        int i = 1000000000;
//        System.out.println(i + i+i);

    }

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        int n = nums.length;
        if (nums == null || n < 4) {
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < n - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < n - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int fourth = n - 1;
                for (int third = j + 1; third < n - 1; third++) {
                    if (third > j + 1 && nums[third] == nums[third - 1]) {
                        continue;
                    }
                    long sum = (long) nums[i] + nums[j] + nums[third] + nums[fourth];
                    while (third < fourth && sum > target) {
                        fourth--;
                    }
                    if(third == fourth){
                        break;
                    }
                    if(sum == target){
                        res.add(Arrays.asList(nums[i], nums[j], nums[third], nums[fourth]));
                    }
                }
            }
        }
        return res;
    }
}
